package com.hu.lsp.service.impl;

import com.hu.lsp.dao.master.UserMasterMapper;
import com.hu.lsp.dao.slave.UserSlaveMasterMapper;
import com.hu.lsp.entity.User;
import com.hu.lsp.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author lsp
 * @Date 2020/5/7 16:06
 * @Version 1.0
 */
@Service

public class UserServiceImpl implements UserService {
    @Autowired
    private UserMasterMapper userMapper;
    @Autowired
    private UserSlaveMasterMapper slaveuserMapper;

    //@DataSource(name = DataSourceNames.SLAVE)
    @Override
    public User selectByPrimaryKey(String id) {
        return userMapper.selectByPrimaryKey(id);
    }


    /**
     * springboot的多数据 可以注入到service上  注入的是方法，也可以注入到dao的方法上  。
     * @param id
     * @return
     */
    //@DataSource(name = DataSourceNames.SLAVE)
    @Override
    public User selectBytestBD(String id) {
        return  slaveuserMapper.selectByPrimaryKey(id);
    }


    /**
     * 配置了jta 事务是全局的。保证了一致性。
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> updateById(String id) {
        Map<String, Object>  map = new HashMap<>();
        try {
            User u =  new User();
            u.setId(id);
            u.setUserName("lsp");
            userMapper.updateByPrimaryKeySelective(u);
            slaveuserMapper.updateByPrimaryKeySelective(u);
          //  int a =1/0;
            map.put("start",200);
        }catch (Exception e){
            map.put("start",201);
            e.printStackTrace();
            throw new RuntimeException("自定义异常。。。。。");
        }
        return map;
    }

}
